﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using FTchina.DAL;
using System.Data.SqlClient;
using System.Data;
using FTchina.Library;
using FTchina.Models;
using PWMIS.DataMap.Entity;
using System.Text.RegularExpressions;
namespace FTchina.Logic
{


    public class ReportSqlMod
    {
        /// <summary>
        /// 字段名称        
        /// </summary>
        public string ColumID { get; set; }
        /// <summary>
        /// 字段值
        /// </summary>
        public string ColumValue { get; set; }
    }

    /// <summary>
    ///ReportLogic 的摘要说明
    /// </summary>
    public class ReportLogic
    {

        public ReportLogic()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }


        #region 表单权限

        /// <summary>
        /// 检查用户是否有当前表单的访问权限
        /// </summary>
        /// <param name="guid"></param>
        public static void CheckUserRight(string guid)
        {

            Cquery_ReportPermission Crps = new Cquery_ReportPermission();
            OQLCompare cmp = new OQLCompare(Crps);
            OQLCompare cmpResult = (cmp.Comparer(Crps.UID, OQLCompare.CompareType.Equal, MasterHelper.UID)
                & cmp.Comparer(Crps.Guid, OQLCompare.CompareType.Equal, guid));
            OQL q = new OQL(Crps);
            q.Select().Where(cmpResult);
            IList<Cquery_ReportPermission> list = EntityQuery<Cquery_ReportPermission>.QueryList(q, Crps);
            if (list.Count == 0)
            {
                HttpContext.Current.Response.Write(MasterHelper.UName + "无权访问此表单");
                HttpContext.Current.Response.End();
            }
        }
        #endregion

        #region Ntext保存单独处理
        /// <summary>
        /// 更新自定义SQL语句，Ntext单独处理
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="SqlString"></param>
        /// <returns></returns>

        public static Boolean UpdateSqlString(string guid, string SqlString)
        {
            string sql =
             "update CQuery_ReportList set SqlString=@SqlString where guid=@guid";
            SqlParameter[] para = new SqlParameter[]
                {					
                    new SqlParameter("@SqlString",System.Data.SqlDbType.NText),
                    new SqlParameter("@guid",guid) 
                };
            para[0].Value = SqlString;
            int newId = DBHelper.ExecuteCommand(sql, para);
            return newId > 0;
        }
        #endregion


        #region 表单保存生成SQL
        /// <summary>
        /// 更新列
        /// </summary>
        /// <param name="adohelper">PWMIS.DataProvider.Data.AdoHelper</param>
        /// <param name="Rsm">List<ReportSqlMod> </param>
        /// <param name="Table"></param>
        /// <param name="guid"></param>
        /// <param name="UpdateSql"></param>
        /// <param name="Paras"></param>
        public static void UpdateColums(PWMIS.DataProvider.Data.AdoHelper adohelper, List<ReportSqlMod> Rsm, string Table, ReportSqlMod guid, ref string UpdateSql, ref IDataParameter[] Paras)
        {
            string sql = "update " + Table + " set ";

            foreach (ReportSqlMod item in Rsm)
            {
                sql += item.ColumID + "=" + adohelper.GetParameterChar + item.ColumID + ",";
            }
            sql = sql.TrimEnd(',');
            sql += "  where " + guid.ColumID + "=" + adohelper.GetParameterChar + guid.ColumID + "";


            List<IDataParameter> ilist = new List<IDataParameter>();

            foreach (ReportSqlMod item in Rsm)
            {//列值
                IDataParameter ida = adohelper.GetParameter();
                ida.ParameterName = item.ColumID;
                ida.Value = item.ColumValue;
                ilist.Add(ida);
            }
            ilist.Add(adohelper.GetParameter(guid.ColumID, guid.ColumValue));
            IDataParameter[] para = ilist.ToArray();


            UpdateSql = sql;
            Paras = para;

        }

        /// <summary>
        /// 插入列
        /// </summary>
        /// <param name="Rsm"></param>
        /// <param name="Table"></param>
        /// <param name="InsertSql"></param>
        /// <param name="Paras"></param>
        public static void InsertColums(PWMIS.DataProvider.Data.AdoHelper adohelper, List<ReportSqlMod> Rsm, string Table, ref string InsertSql, ref IDataParameter[] Paras)
        {
            string sql = "insert into  " + Table + " ( ";

            foreach (ReportSqlMod item in Rsm)
            {
                sql += "[" + item.ColumID + "],";
            }
            sql = sql.TrimEnd(',');
            sql += ") values ( ";
            foreach (ReportSqlMod item in Rsm)
            {
                sql += adohelper.GetParameterChar + item.ColumID + ",";
            }
            sql = sql.TrimEnd(',');
            sql += ") ";



            List<IDataParameter> ilist = new List<IDataParameter>();

            foreach (ReportSqlMod item in Rsm)
            {//列值
                IDataParameter ida = adohelper.GetParameter();
                ida.ParameterName = item.ColumID;
                ida.Value = item.ColumValue;
                ilist.Add(ida);
            }
            IDataParameter[] para = ilist.ToArray();


            InsertSql = sql;
            Paras = para;
        }

        #endregion


        #region 系统保留关键字替换
        /// <summary>
        /// 对默认值进行处理{姓名}{账户}{Now}
        /// </summary>
        /// <param name="Dfv"></param>
        /// <returns></returns>
        public static string DefaultValueFormat(string Dfv)
        {
            string tmp = Dfv;
            tmp = tmp.Replace("$姓名$", MasterHelper.UName);
            tmp = tmp.Replace("$账户$", MasterHelper.UID);
            tmp = tmp.Replace("$Now$", DateTime.Now.ToString());
            return tmp;
        }
        #endregion


        #region 根据SQL语句提取字段
        public static DataTable GetColumsBySql(string sql)
        {
            sql = ReplaceSpace(sql);
            DataTable dt = new DataTable();
            MatchCollection mc = Regex.Matches(sql, @"([^\s=]+)=({)(.*?)(})");
           // LogHelper.Debug(sql+mc.Count);
            foreach (Match m in mc)
            {
                string key = m.Groups[1].Value;
                if (key.Split('.').Length == 2)
                {
                    key = key.Split('.')[1];
                }
                try
                {
                    // string value=m.Groups[3].Value;
                    //LogHelper.Debug("key" + key);
                    //LogHelper.Debug("value" + m.Groups[3].Value);
                    DataColumn dc = new DataColumn(key);
                    dt.Columns.Add(dc);
                }
                catch(Exception er)
                {
                    LogHelper.Error(er.Message);
                    continue;
                }

            }
            return dt;
        }
        /// <summary>
        /// 去除多余的空格
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        private static string ReplaceSpace(string sql)
        {
            sql = Regex.Replace(sql, @"\s+", " ");//合并多个连续空格
            sql = sql.Replace(" >", ">").Replace(" <", "<").Replace(" =", "=").Replace("!=", "!=");//去除多余空格;
            return sql;
        }


        /// <summary>
        /// 去除替换模式的替换标记
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static string RemoveFormater(string sql)
        {
            sql = sql.Replace("{", "").Replace("}", "");
          
            return sql;
        }

        /// <summary>
        /// 情况太多，不合适。
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static string AddFormater(string sql)
        {
            sql = ReplaceSpace(sql);
           
            MatchCollection mc = Regex.Matches(sql, @"([^\s=]+)([>=|<=|=|<>|!=])(.*?)");

            foreach (Match m in mc)
            {
                string key = m.Groups[1].Value;
                string value = m.Groups[3].Value;
               
                sql = Regex.Replace(sql, @"([^\s=]+)([>=|<=|=|<>|!=])(.*?)", key+"="+value);//合并多个连续空格
               // LogHelper.Debug("m" + key+value);

            }
          //  LogHelper.Debug(sql);
            return sql;
        }
        #endregion


        #region 获取替换模式的sql语句，主要是替换xx.u={'34'} 为控件取值
        public static void getReplaceModeSql(string text, string ColumID, ref string SqlFrom)
        {
            //LogHelper.Debug("text" + text + "ColumID" + ColumID+SqlFrom);
            SqlFrom = ReplaceSpace(SqlFrom.ToUpper());
            MatchCollection mc = Regex.Matches(SqlFrom, @"([^\s=]+)=({)(.*?)(})");
            //LogHelper.Debug("mc" + mc.Count);

            foreach (Match m in mc)
            {
                //LogHelper.Debug(m.Groups[1].Value );
                //LogHelper.Debug(ColumID);
                string[] key = m.Groups[1].Value.Split('.');
                string OP = string.Empty;
                if (key.Length == 2)
                {//如果是X.UU='e'额样式，要还原回去
                    OP = key[1];
                    text = text.Replace(ColumID, key[0] + "." + ColumID);
                }
                else
                {
                    OP = key[0];
                }
                if (OP == ColumID)
                {
                    SqlFrom = SqlFrom.Replace(m.Groups[1].Value + "={" + m.Groups[3].Value + "}", text);
                }

            }
           // LogHelper.Debug(SqlFrom);

            //   LogHelper.Debug(SqlFrom);

        }
        #endregion
    }
}